import { getCurrentTime, staticService } from '@/utils/ruoyi';
import { ImageModeVo } from '@/views/bus/jqtSpreadLink/mode/imageMode.vue';
import { ImageTextModeVo } from '@/views/bus/jqtSpreadLink/mode/imageTextMode.vue';
import { DialogModeVo } from '@/views/bus/jqtSpreadLink/mode/dialogMode.vue';
import { DialogModeSetVo } from '@/views/bus/jqtSpreadLink/mode/dialogSetMode.vue';

/**
 * 生成图片Html模板
 * @param data 包含全部内容
 */
export const generateImageHtmlTemplate = (data:ImageModeVo): string => {
  return `
    <div class="generated-container" style="position: relative; width: 100%; height: 100%; padding: 2px; box-sizing: border-box;">

      <!-- 可滚动的图片区域 -->
      <div class="image-scroll-container" style="width: 100%; height: 100%; overflow-y: auto; -webkit-overflow-scrolling: touch;">
        ${data.bodyImg
          ? data.bodyImg
            .split(',') // 按逗号分割字符串
            .filter(img => img.trim() !== '') // 过滤空字符串或空格
            .map(img => `<img src="${staticService(img.trim())}" style="width: 100%; display: block;" class="top-image">`)
            .join('') // 转为字符串插入
          : ''
        }
      </div>

      <!-- 右侧悬浮图片：注意层级和定位 -->
      ${data.rightImg ? `<img src="${staticService(data.rightImg)}" style="position: absolute; top: 20%; right: 10px; transform: translateY(-50%); max-width: 60px; height: auto; z-index: 2;" class="right-image">` : ''}

      <!-- 底部悬浮图片：注意层级和定位 -->
      ${data.bottomImg ? `<img src="${staticService(data.bottomImg)}" style="position: absolute; left: 50%; transform: translateX(-50%); bottom: ${data.bottomDistance}px; max-width: 100%; height: auto; z-index: 2;" class="bottom-image">` : ''}

    </div>
  `;
}

/**
 * 生成图片文字Html模板
 * @param data ImageTextModeVo[] 组件列表
 * @returns string HTML 字符串
 */
export const generateImageTextHtmlTemplate = (data: ImageTextModeVo[]): string => {
  if (!data || !Array.isArray(data) || data.length === 0) {
    return ''; // 空数组或无效输入
  }

  // 生成每个 item 的 HTML
  const itemsHtml = data
    .map((item: ImageTextModeVo) => {
      if (!item || !item.content || !item.type) return ''; // 跳过无效项

      const { type, content, contentPosition } = item;
      let elementHtml = '';
      let style = '';

      // 生成内容：文字 or 图片
      if (type === 'text') {
        elementHtml = `<div>${content}</div>`;
      } else if (type === 'img' && content) {
        elementHtml = `
          <img
            src="${staticService(content)}"
            style="max-width: 100%; height: auto; display: block;"
            onerror="this.onerror=null; this.src='https://via.placeholder.com/150';">
        `;
      } else {
        return ''; // 类型不支持
      }

      // 设置定位样式
      switch (contentPosition) {
        case '0': // 正常
          style = 'position: static;';
          break;
        case '1': // 顶部悬浮
          style = 'position: fixed; top: 5%; left: 50%; transform: translateX(-50%); max-width: 100%; height: auto; z-index: 1000;';
          break;
        case '2': // 底部悬浮
          style = 'position: fixed; bottom: 10%; left: 50%; transform: translateX(-50%); max-width: 100%; height: auto; z-index: 1000;';
          break;
        case '3': // 左侧悬浮
          style = 'position: absolute; top: 20%; left: 10px; transform: translateY(-50%); max-width: 60px; height: auto; z-index: 2;';
          break;
        case '4': // 右侧悬浮
          style = 'position: absolute; top: 20%; right: 10px; transform: translateY(-50%); max-width: 60px; height: auto; z-index: 2;';
          break;
        default:
          style = 'position: static;';
      }

      // 悬浮组件需要绝对定位，正常位置在滚动区内
      if (['1', '2', '3', '4'].includes(contentPosition || '')) {
        return `<div style="${style}">${elementHtml}</div>`;
      }

      // 正常位置的内容放入滚动区
      return `<div style="display: inline-block;">${elementHtml}</div>`;
    })
    .filter(html => html !== '') // 过滤空字符串
    .join('');
  // 返回完整结构
  return `
    <div class="generated-container" style="position: relative; width: 100%; min-height: 200px; padding: 2px; box-sizing: border-box;">
      <!-- 可滚动内容区 -->
      <div class="scrollable-content" style="width: 100%; height: 100%; overflow-y: auto; -webkit-overflow-scrolling: touch; padding: 10px;">
        ${itemsHtml}
      </div>
    </div>
  `;
};

/**
 * 生成问答模式Html模板
 * @param data 包含全部内容
 * @param dataSet 包含全部内容
 */
export const generateDialogModeTemplate = (data:DialogModeVo,dataSet:DialogModeSetVo): string => {
  // 验证数据有效性
  if (!data) {
    return '';
  }

  // 生成头部HTML
  let headerHtml = '';
  if (data?.floatCard?.switch === '1') {
    // 生成头部标签HTML
    let headerTagsHtml = '';
    if(data?.floatCard?.labels){
      const headerTags = data.floatCard.labels.split(',');
      if (headerTags && Array.isArray(headerTags) && headerTags.length > 0) {
        headerTagsHtml = headerTags
          .filter(tag => tag.trim() !== '')
          .map(tag => `
        <li style="margin: 0 8px 0 0; border-radius: 20px; padding: 1px 8px; border: 1px solid #aaaaaa; font-size: 13px; color: #999999; text-wrap: nowrap; overflow: hidden;">
          ${tag}
        </li>
      `)
          .join('');
        headerTagsHtml = headerTagsHtml ? `<ul class="tags" style="display: flex; list-style: none; padding: 0; margin: 0;">${headerTagsHtml}</ul>` : '';
      }
    }
    headerHtml = `
      <!-- 头部占位符 -->
      <div class="header-placeholder" style="height: 90px;"></div>
      <div class="header" style="display: flex; position: absolute; top: 0; left: 50%; transform: translateX(-50%); max-width: 500px; width: 100%; background-color: #ffffff; box-sizing: border-box; padding: 15px; z-index: 999999; box-shadow: 0 5px 8px -3px rgba(0, 0, 0, 0.2);">
        <img class="img" src="${staticService(data?.floatCard?.picture)}"style="width: 60px; height: 60px;" />
        <div class="header-main" style="display: flex; flex-direction: column; justify-content: space-between; flex: 1; margin-left: 10px; box-sizing: border-box; padding: 4px 0;">
          <span class="title" style="font-size: 18px; font-weight: 600;">${data?.floatCard?.title || ''}</span>
          ${headerTagsHtml}
        </div>
      </div>
    `;
  }

  // 横幅图片HTML
  const bannerHtml = data.topImg
    ? `<img src="${staticService(data.topImg)}" class="banner-img" style="width: 100%; height: auto; display: block;" />`
    : '';


  // 生成图表卡片HTML
  let chartCardHtml = '';
  if (data?.headCard?.switch === '1') {
    // 生成图表标签HTML
    let chartTagsHtml = '';
    if(data?.headCard?.labels){
      const chartTags = data.headCard.labels.split(',');
      if (chartTags && Array.isArray(chartTags) && chartTags.length > 0) {
        chartTagsHtml = chartTags
          .filter(tag => tag.trim() !== '')
          .map(tag => `
        <li style="padding: 2px 5px; border: 1px solid #ed4c18; color: #ed4c18; border-radius: 2px; font-size: 13px; margin: 0 8px 2px 0; text-wrap: nowrap; overflow: hidden;">
          ${tag}
        </li>
      `)
          .join('');
        chartTagsHtml = chartTagsHtml ? `<ul class="tags" style="display: flex; list-style: none; padding: 0; margin: 0;">${chartTagsHtml}</ul>` : '';
      }
    }
    chartCardHtml = `
      <div class="chart" style="display: flex; background-color: #ffffff; border-radius: 4px; margin: 15px; padding: 15px;">
        <img class="img-large" src="${staticService(data?.headCard?.picture)}" style="width: 90px; height: 90px;" />
        <div class="chart-main" style="flex: 1; display: flex; flex-direction: column; justify-content: space-between; margin: 0 0 0 10px; overflow: hidden;">
          <span class="title" style="font-size: 18px; font-weight: 600;">${data?.headCard?.title || ''}</span>
          ${chartTagsHtml}
          <span>${data?.headCard?.subtitle || ''}</span>
        </div>
      </div>
    `;
  }

  // 提示文本HTML
  const hintTextHtml = data.processTitle
    ? `<div class="hint-text" style="margin: 20px 5px; font-size: 15px; color: #616060; text-align: center;">${data.processTitle}</div>`
    : '';

  // 生成消息列表HTML
  let messagesHtml = '';
  if (dataSet?.welcomeMsg?.msg && Array.isArray(dataSet?.welcomeMsg?.msg) && dataSet?.welcomeMsg?.msg.length > 0) {
    messagesHtml = dataSet?.welcomeMsg?.msg
      .map(msg => {
        if (!msg) {
          return '';
        }

        // 渲染消息头部（仅客服消息显示）
        const messageHeader = data?.customer?.switch === '1'?`
            <div class="content-header" style="display: flex; align-items: center; padding: 0 0 12px 12px;">
              <span class="username" style="font-size: 16px; font-weight: 600; color: #333333; margin-right: 10px;">${data.customer.name}</span>
              <span class="timestamp" style="font-size: 14px; font-weight: 300; color: #999;">${getCurrentTime()}</span>
            </div>
          `:'';

        // 气泡三角符号
        const triangle = `<span style="position: absolute; top: 22px; transform: translate(-5px, -50%); left: 0; content: ' '; border-top: 8px solid transparent; border-bottom: 8px solid transparent; border-right: 8px solid #FFFFFF; width: 0; height: 0;"></span>`;

        return `
          <div class="item" style="display: flex; font-size: 14px; animation: myfirst .8s;}">
            <img class="img" src="${staticService(data.customerPicture)}" style="width: 40px; height: 40px; border-radius: 3px;" />
            <div class="content" style="display: flex; flex-direction: column; line-height: 20px; margin: 0; overflow: hidden; max-width: calc(100% - 70px); flex: 1;">
              ${messageHeader}
              <div class="message">
                <span style="float: left; font-size: 15px; margin: 0 10px; line-height: 24px; max-width: calc(100% - 50px); padding: 10px; border-radius: 4px; position: relative; word-break: break-all; background: #fff;">
                  ${msg}
                  ${triangle}
                </span>
              </div>
            </div>
          </div>
        `;
      })
      .filter(html => html !== '')
      .join('');
  }

  // 生成底部按钮HTML
  let actionButtonsHtml = `<div class="action-panel" style="height: auto; bottom: 0; width: 100%; max-width: 500px; background-color: #f5f5f5;">
          <div class="action-panel_btns" style="height: auto; padding: 15px 15px 70px 15px; display: flex; margin: 0; grid-gap: 10px; grid-template-columns: repeat(var(--num), 1fr); animation: opacity .6s;">
              <button style="background-color: #28C76F; list-style: none; padding: 10px 15px; font-size: 15px; color: #FFFFFF; border-radius: 5px;width: 100%; box-sizing: border-box; text-align: center; cursor: pointer; border: none;">需要</button>
              <button style="background-color: #28C76F; list-style: none; padding: 10px 15px; font-size: 15px; color: #FFFFFF; border-radius: 5px;width: 100%; box-sizing: border-box; text-align: center; cursor: pointer; border: none;">不需要</button>
          </div>
        </div>`;

  // 生成底部按钮HTML
  let actionButtonsHtml2 = `<div class="action-panel" style="height: auto; bottom: 0; width: 100%; max-width: 500px; background-color: #f5f5f5;">
          <div class="action-panel_btns" style="height: auto; padding: 15px 15px 70px 15px; display: flex; margin: 0; grid-gap: 10px; grid-template-columns: repeat(var(--num), 1fr); animation: opacity .6s;">
              <button style="background-color: #28C76F; list-style: none; padding: 10px 15px; font-size: 15px; color: #FFFFFF; border-radius: 5px;width: 100%; box-sizing: border-box; text-align: center; cursor: pointer; border: none;">点击添加微信</button>

          </div>
        </div>`;

  // 组装并返回完整HTML结构
  return `
    <div class="cotainer style-light" style="max-width: 500px; margin: 0 auto; background-color: #f5f5f5;">

      <!-- 固定头部 -->
      ${headerHtml}

      <!-- 横幅图片 -->
      ${bannerHtml}

      <!-- 图表卡片 -->
      ${chartCardHtml}

      <!-- 在线对话提示 -->
      ${hintTextHtml}

      <!-- 聊天消息列表 -->
      <div class="chart-list" style="width: 100%; display: flex; flex-direction: column; padding: 15px 10px 15px; box-sizing: border-box; height: auto; flex-shrink: 0;">
        ${messagesHtml}
      </div>

      <!-- 底部操作按钮 -->
      ${actionButtonsHtml}

      <!-- 底部操作按钮添加微信 -->
      ${actionButtonsHtml2}
    </div>
  `;
};
